
angular.module('QualifyInspection')

.controller('QualifyInspection.HomeCtrl', ['$scope', 'QualifyInspectionMaster', 'DevicePort', 'imanDialog',
    function ($scope, QualifyInspectionMaster, DevicePort, imanDialog) {
        $scope.data = {
            barcodeNum: 0
        };

        $scope.data.gridOptions = {
            columnDefs: [ 
                { col: 'Barcode', name: '芯片ID' },
                { col: 'MOCode', name: '工单号' },
                { col: 'MOLotNumber', name: '生产批次' },
                { col: 'ItemMasterCode', name: '料号' },
                { col: 'ItemMasterName', name: '品名' },
                { col: 'Specification', name: '规格' },
                { col: 'WorkName', name: '当前作业' }
            ],
            data: []
        };

        var _barcodes = [],
            _isProcessing = false;

        $scope.submit = function () {
            if (_barcodes.length === 0) {
                imanDialog.toastBottom('请扫描合格品');
                return;
            }
            QualifyInspectionMaster.submit(_barcodes).then(function (barcodeMaster) {
                $scope.data.gridOptions.data = [];
                _barcodes = [];
                $scope.data.barcodeNum = 0;
                imanDialog.toastBottom('合格品检验成功');
            });
        };

        $scope.$on('$ionicView.afterEnter', function () {
            DevicePort.open({
                device: 0,
                baudrate: 115200,
                parseFn: true
            });
        });
        $scope.$on('$ionicView.beforeLeave', function () {
            DevicePort.close();
        });
        $scope.$on('$destroy', function () {
            DevicePort.close();
        });

        $scope.$on('devicePort.DataReceived', function (e, barcode) {
            if (_isProcessing) {
                return;
            }
            if (!checkValid(barcode)) {
                imanDialog.toastBottom('该料品已存在');
                return;
            }
            _isProcessing = true;
            imanDialog.showLoading();
            QualifyInspectionMaster.scanCode(barcode).then(function (barcodeMaster) {
                $scope.data.gridOptions.data.unshift(barcodeMaster);
                $scope.data.gridOptions.data = angular.copy($scope.data.gridOptions.data);
                _barcodes.push(barcodeMaster.Barcode);
                $scope.data.barcodeNum++;
            }).finally(function () {
                _isProcessing = false;
                imanDialog.hideLoading();
            });
        });

        function checkValid (barcode) {
            var valid = true;
            for (var i = 0, len = _barcodes.length; i < len; i++) {
                if (_barcodes[i] === barcode) {
                    valid = false;
                    break;
                }
            }
            return valid;
        }
    }
]);